package com.example.dangerouscargodriver.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.baiju.style.wheelpicker.WheelPickerView;
import com.baiju.style.wheelpicker.bean.WheelItemBean;
import com.baiju.style.wheelpicker.config.WheelPickerConfig;
import com.baiju.style.wheelpicker.listener.OnWheelItemClickListener;
import com.example.dangerouscargodriver.R;
import com.example.dangerouscargodriver.adapter.TruckInfoAdapter;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.EnterPlatformInfoController;
import com.example.dangerouscargodriver.controller.IControllerEventListener;
import com.example.dangerouscargodriver.entry.CompanyInfo;
import com.example.dangerouscargodriver.entry.CompanyMainInfo;
import com.example.dangerouscargodriver.entry.CompanyTruckInfo;
import com.example.dangerouscargodriver.event.Event;
import com.example.dangerouscargodriver.event.LoadHttpResourceStatus;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CompanyTruckListActivity extends HttpRequestActivity implements View.OnClickListener {

	private static final String TAG = "TruckListActivity";
	private static final int MSG_LOAD_ENTER_ATTR_DONE = 0;

	private MyControllerEventListener mControllerListener = null;
	private MyHandler mHandler = null;
	private TruckInfoAdapter mAdapter = null;
	private List<CompanyTruckInfo> mTruckListArray = null;

	private ActionBar mActionBar = null;

	private WheelPickerView mCompanyPickerView = null;
	private ArrayList<WheelItemBean> mCompanyList = null;
	private WheelItemBean mSelectedBean = null;

	private LinearLayout mCompanySelector = null;
	private TextView mCompanyName = null;

	private Button mActionAddCar = null;

	private RecyclerView mTruckListRv = null;

	private boolean mFirstStart = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.initHttpComponent(CompanyTruckListActivity.class);
		setContentView(R.layout.activity_company_truck_list);
		AppManager.getAppManager().addActivity(this);

		mControllerListener = new MyControllerEventListener();
		mHandler = new MyHandler(this);
		mAdapter = new TruckInfoAdapter();

		mCompanyPickerView = new WheelPickerView();
		mCompanyList = new ArrayList<WheelItemBean>();
		mCompanyPickerView.init(this, mCompanyList);

		mCompanyName = findViewById(R.id.tv_text_company_name);
		mCompanySelector = findViewById(R.id.layout_company_selector);
		mCompanySelector.setOnClickListener(this);

		mActionAddCar = findViewById(R.id.btn_company_add_car);
		mActionAddCar.setOnClickListener(this);

		mTruckListRv = findViewById(R.id.rv_truck_list);
		LinearLayoutManager layoutManager = new LinearLayoutManager(getBaseContext());
		mTruckListRv.setLayoutManager(layoutManager);
		mTruckListRv.setAdapter(mAdapter);

		mActionBar = findViewById(R.id.actionBarCarList);
		mActionBar.setOnBackClickListener( new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		EnterPlatformInfoController.Instance().attachControllerListener(CompanyTruckListActivity.class,
				mControllerListener);
	}

	private void executeGetCarInfo(){
		HashMap<String, String> header = new HashMap<String, String>();
		header.put("token", AuthController.Instance().getToken());

		HashMap<String, String> param = new HashMap<String, String>();
		param.put("cid", mSelectedBean.getId());

		sendHttpRequest(
				IHttpRequest.RequestMethod.GET_METHOD,
				RemoteAPI.REQUEST_V1_USER_REGISTER_TRUCK,
				header,
				param,
				RemoteAPICmd.REQUEST_V1_USER_REGISTER_TRUCK);
	}

	private void refreshCompanyView(){
		initCompanyInfo();
		if(mCompanyList.size() > 0){
			mCompanyName.setText(mSelectedBean.getName());
		}
	}

	private void refreshTruckListView(){
		mAdapter.clearData();
		mAdapter.appendData(mTruckListArray);
	}

	private void initCompanyInfo(){
		List<CompanyInfo> companyInfos = EnterPlatformInfoController.Instance().getCompanyInfoList();
		Log.d(TAG, "companyInfos: " + companyInfos.toString());
		if(companyInfos != null && companyInfos.size() > 0){
			mCompanyList.clear();
			for(int index = 0; index < companyInfos.size(); index++) {
				WheelItemBean bean = new WheelItemBean();
				bean.setId(companyInfos.get(index).getCid());
				bean.setName(companyInfos.get(index).getName());

				mCompanyList.add(bean);
			}
			mSelectedBean = mCompanyList.get(0);
		}
	}

	private void showCompanyListSelector(){
		if(mCompanyList.size() <= 0){
			ToastUtils.showLongToast(this, "获取公司信息异常！");
		}
		else{
			WheelPickerConfig pickerConfig = new WheelPickerConfig.Builder()
					.title("选择类型")
					.visibleItemsCount(8)
					.defaultItem(mSelectedBean.getName())
					.itemCyclic(false)
					.setCustomItemLayout(R.layout.item_city)//自定义item的布局
					.setCustomItemTextViewId(R.id.item_city_name_tv)
					.build();
			pickerConfig.setTitleBackgroundColorStr("#FFD401");

			mCompanyPickerView.setConfig(pickerConfig);
			mCompanyPickerView.setOnItemClickListener(new OnWheelItemClickListener() {
				@Override
				public void onSelected(WheelItemBean type) {
					if(type != null){
						if(mSelectedBean.getId().equals(type.getId())){

						}
						else{
							mSelectedBean = type;
							mTruckListArray.clear();
							mAdapter.clearData();
							executeGetCarInfo();
						}
					}
				}

				@Override
				public void onCancel() {
					/**/
				}
			});
			mCompanyPickerView.showWheelPicker();
		}
	}

	@Override
	protected void onHttpResponse(int actionId, String response) {
		try {
			JSONObject res = new JSONObject(response);
			Gson gson = new Gson();
			if(actionId == RemoteAPICmd.REQUEST_V1_USER_REGISTER_TRUCK){
				Log.d(TAG, "onResponse: " + response);
				dismissLoadingDialog();
				ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
				if(responseInfo != null && responseInfo.getStatus() == 1){
					Type type = new TypeToken<List<CompanyTruckInfo>>() {}.getType();
					mTruckListArray = gson.fromJson(res.getJSONArray("data").toString(), type);
					refreshTruckListView();
				}
			}
			else{

			}
		}
		catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onHttpErrorResponse(int actionId, String response) {
		if(actionId == RemoteAPICmd.REQUEST_V1_USER_REGISTER_TRUCK){
			dismissLoadingDialog();
			ToastUtils.showLongToast(this, "获取车辆信息失败");
		}
		else{
			/**/
		}
	}

	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.layout_company_selector){
			showCompanyListSelector();
		}
		else if(v.getId() == R.id.btn_company_add_car){
			Intent intent = new Intent(this, CompanyAddTruckActivity.class);
			intent.putExtra("cid", mSelectedBean.getId());
			intent.putExtra("cname", mSelectedBean.getName());
			startActivity(intent);
		}
		else {

		}
	}

	@Override
	public void onResume(){
		super.onResume();
		if(mFirstStart){
			mFirstStart = false;
		}
		else {
			executeGetCarInfo();
		}
	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		Log.d(TAG, "onDestroy");
		EnterPlatformInfoController.Instance().unAttachControllerListener(
				CompanyTruckListActivity.class,
				mControllerListener);
	}

	private class MyHandler extends Handler {
		WeakReference<CompanyTruckListActivity> mActivity;

		MyHandler(CompanyTruckListActivity activity) {
			mActivity = new WeakReference<CompanyTruckListActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			CompanyTruckListActivity activity = mActivity.get();
			switch (msg.what){
				case MSG_LOAD_ENTER_ATTR_DONE:
					activity.showLoadingDialog();
					activity.refreshCompanyView();
					activity.executeGetCarInfo();
					break;
			}
		}
	}

	private class MyControllerEventListener implements IControllerEventListener {

		@Override
		public void onEvent(int eventId, String json) {
			if(eventId == Event.EVENT_LOAD_HTTP_ENTER_STATUS){
				Gson gson = new Gson();
				LoadHttpResourceStatus status = gson.fromJson(json, LoadHttpResourceStatus.class);
				Log.d(TAG, "onEvent: " + status.toJson());
				if(status.getWhat() == EnterPlatformInfoController.LOAD_ENTER_STATUS_DONE){
					Message msg = new Message();
					msg.what = MSG_LOAD_ENTER_ATTR_DONE;
					mHandler.sendMessage(msg);
				}
			}
		}
	}
}